import axios from 'axios'
import { Toast,Dialog } from 'vant';
import {loading} from '@/utils/common'
import Cookies from './auth'
import router from '@/router'
import {H5CallAPPFuction,myJsDailog} from '@/utils/common'
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, 
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// request拦截器
service.interceptors.request.use(config => {
  if(!config.unLoading){
    loading.open()
  }
  const token = Cookies.get('token')
  if (token) {
		//config.headers['Authorization'] = token 
    config.headers['token'] = token
	}
  return config
}, error => {
  Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use(res => {
  loading.close()
  if(res.data.code == -1 || res.data.message=="walletAddress is not null" || res.data.message=="钱包地址不能为空"){
    myJsDailog({
      message:res.data.message,
      showCancelButton:false
    },()=>{
        try {
            H5CallAPPFuction('backToHome')   // 调用app方法处理返回
        } catch (error) {
            router.back()
        }
    })
    // Dialog.confirm({
    //   title: '提示信息',
    //   message:'登录已过期，请重新登录', // res.data.message
    // })
    // .then(() => {
    //   try {
    //       H5CallAPPFuction('backToHome')   // 调用app方法处理返回
    //   } catch (error) {
    //       router.back()
    //   }
    // })
    // .catch(() => {
        
    // });
  }
  return res
}, error => {
  loading.close()
  if(error.response.status == 500){
    Toast(error.response.data.message)
    return Promise.resolve(error.response)
  }else{
    return Promise.reject(error)
  }
})

export default service

